package com.malbbmsomanager.reports;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import com.malbbmsomanager.DM_BBM_InvoiceMenu;
import com.malbbmsomanager.R;
import com.malbbmsomanager.print.DM_BBM_InvoiceSalesOrder_PrintPreview;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class DM_BBM_Outlet_FreeIssue_Summary extends Activity implements
ActionBar.OnNavigationListener{

	private static final String TAG = null;
	// Database Name.
	private static final String DATABASE_NAME = "dminvoicemanagerbbm.db";
	// ****Main Transaction Table****
	private String FORDHED_TABLE = "FOrdHed";
	private String FORDDET_TABLE = "FOrdDet";
	String item_result_1 = "0", item_result_2 = "0", item_result_3 = "0",
			item_result_4 = "0", item_result_5 = "0", item_result_6 = "0";

	int toDayTag = 0;
	int dayFreeQty = 0;
	int totFreeQty = 0;
	DecimalFormat numberFormat = new DecimalFormat("#.000000");
	DecimalFormat numberFormatAmt = new DecimalFormat("#,###,###.00");
	MathContext mc = new MathContext(2, RoundingMode.HALF_UP);
	
	EditText dmreportfromdate, dmreporttodate, dmdisplayrepname;
	TextView txtHeadingReports, totalSum, totalTonage;
	TextView recordtot_1, recordtot_2, recordtot_3, recordtot_4, recordtot_5,
			recordtot_6;

	String currentReportName, selectFromDate, selectToDate, currentUserTemp,
			currentUserPrefix, UserLocCode, selectFromDateNow, selectToDateNow;

	SimpleDateFormat originalFormat = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
	Date date, LoadingFromDate, LoadingToDate, LoadingOriDate;
	private ActionBar actionBar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_outlet_freeissue_summary);

		actionBar = getActionBar();
		// Hide the action bar title
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);
		
		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "item_result_0", "item_result_1",
				"item_result_2", "item_result_3", "item_result_4",
				"item_result_5" };

		int[] totrdes = new int[] { R.id.record_0, R.id.record_1,
				R.id.record_2, R.id.record_3, R.id.record_4, R.id.record_5 };

		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;
		String query;
		query = "SELECT * FROM FOrdHed Where Active_State != '1' GROUP BY DebCode";
		// ***Select sum queries need seperately 8 to for the combinations
		allrowitemsdes = mydb.rawQuery(query, null);
		Log.v(TAG, "Count:" + allrowitemsdes.getCount());
		String PreTxnDate = "000";
		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					String ParentRefNo = allrowitemsdes.getString(1);
					String RetailerNo = allrowitemsdes.getString(8);
					String RetailerName = allrowitemsdes.getString(38);
					
					Cursor displaySummary = null;
					String querySummary;
					
					querySummary = "SELECT FH.RefNo,FD.Itemcode,FD.freeqty,FD.ItemName FROM FOrdDet FD,FOrdHed FH Where FH.RefNo = FD.RefNo AND FH.DebCode = '"+ RetailerNo +"'";
					displaySummary = mydb.rawQuery(querySummary, null);
					
					if (displaySummary != null) {
						if (displaySummary.getCount() > 0) {
							int printIndex = 0;
							while (displaySummary.moveToNext()) {
								
								String RefNo = displaySummary.getString(0);
								String Itemcode = displaySummary.getString(1);
								String freeqty = displaySummary.getString(2);
								String ItemName = displaySummary.getString(3);
							
								//dayFreeQty
								if(freeqty.length() !=0){
									int freeqtyVal = Integer.parseInt(freeqty);
									dayFreeQty = dayFreeQty + freeqtyVal;
								}
								
								if(dayFreeQty > 0){
									printIndex= printIndex + 1;
									HashMap<String, String> maptrdes = new HashMap<String, String>();
									if(printIndex == 1){
										maptrdes.put("item_result_0", RetailerNo);
										maptrdes.put("item_result_1", RetailerName);
										maptrdes.put("item_result_2", RefNo);
										maptrdes.put("item_result_3", Itemcode);
										maptrdes.put("item_result_4", ItemName);
										maptrdes.put("item_result_5", freeqty);
									}
									else{
										maptrdes.put("item_result_0", "");
										maptrdes.put("item_result_1", "");
										maptrdes.put("item_result_2", RefNo);
										maptrdes.put("item_result_3", Itemcode);
										maptrdes.put("item_result_4", ItemName);
										maptrdes.put("item_result_5", freeqty);
									}
									
									
									// fill in the grid_item layout
									fillMapstrdes.add(maptrdes);
									SimpleAdapter adaptertrdes = new SimpleAdapter(this,
											fillMapstrdes,
											R.layout.dm_bbm_outlet_freeissue_summary_raw,
											fromtrdes, totrdes);
									lvtypedes.setAdapter(adaptertrdes);
								}
							}
						}
					}
				   
					if(dayFreeQty > 0){
						HashMap<String, String> maptrdes = new HashMap<String, String>();
						maptrdes.put("item_result_0", "");
						maptrdes.put("item_result_1", "");
						maptrdes.put("item_result_2", "Total");
						maptrdes.put("item_result_3", "");
						maptrdes.put("item_result_4", "");
						maptrdes.put("item_result_5", "" + dayFreeQty);
						
						// fill in the grid_item layout
						fillMapstrdes.add(maptrdes);
						SimpleAdapter adaptertrdes = new SimpleAdapter(this,
								fillMapstrdes,
								R.layout.dm_bbm_outlet_freeissue_summary_raw,
								fromtrdes, totrdes);
						lvtypedes.setAdapter(adaptertrdes);
						
						//Insert Dummy Record
						HashMap<String, String> maptrdesdum = new HashMap<String, String>();
						maptrdesdum.put("item_result_0", "");
						maptrdesdum.put("item_result_1", "");
						maptrdesdum.put("item_result_2", "");
						maptrdesdum.put("item_result_3", "");
						maptrdesdum.put("item_result_4", "");
						maptrdesdum.put("item_result_5", "");
						
						// fill in the grid_item layout
						fillMapstrdes.add(maptrdesdum);
						SimpleAdapter adaptertrdesdum = new SimpleAdapter(this,
								fillMapstrdes,
								R.layout.dm_bbm_outlet_freeissue_summary_raw,
								fromtrdes, totrdes);
						lvtypedes.setAdapter(adaptertrdesdum);
						
						
						totFreeQty = totFreeQty + dayFreeQty;
						
					}
					dayFreeQty = 0;
				}
			}
		}
       /************Display Report Summary*********************/
		
		HashMap<String, String> maptrdes = new HashMap<String, String>();
		maptrdes.put("item_result_0", "");
		maptrdes.put("item_result_1", "");
		maptrdes.put("item_result_2", "Grand Total");
		maptrdes.put("item_result_3", "");
		maptrdes.put("item_result_4", "");
		maptrdes.put("item_result_5", "" + totFreeQty);
		
		// fill in the grid_item layout
		fillMapstrdes.add(maptrdes);
		SimpleAdapter adaptertrdes = new SimpleAdapter(this,
				fillMapstrdes,
				R.layout.dm_bbm_outlet_freeissue_summary_raw,
				fromtrdes, totrdes);
		lvtypedes.setAdapter(adaptertrdes);
	}
	
	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			LocationFound();
			return true;
		case R.id.action_refresh:
			// refresh
			/*
			 * refreshMenuItem = item; // load the data from server new
			 * SyncData().execute();
			 */
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void LocationFound() {
		// TODO Auto-generated method stub
		
		Intent myIntent = new Intent(DM_BBM_Outlet_FreeIssue_Summary.this,
				DM_BBM_Reports_Generator.class);
		myIntent.putExtra("TAGID", "0/SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}
}
